<template>
  <div class="cover-image" v-loading='loadingImg' >
    <input type="file" ref="upload" style="display:none" @change="starUpload">
    <div class="hc-header">
      <div class="header-left">
        <div class="header-item" style="cursor:default">鲜檬摄影皇室米兰松岗店</div>
        <div class="header-item" style="cursor:pointer" @click="changeImage">更换图片</div>
        <div class="header-item" style="cursor:default">
          对比图功能
          <el-switch
          style="width:30px"
            :disabled = '!afterImg'
            @change="changeContrast"
            v-model="contrast"
            active-color="#13ce66"
            inactive-color="#b5b5b5"
          >
          </el-switch>
        </div>

        <div class="header-item header-slider">
            <div> <i style="cursor:pointer;margin-right:10px" @click="changeSliderBtn(1)" class="el-icon-zoom-out"></i> </div>
            <div> <el-slider :disabled = '!afterImg' style="width:200px" @input="changeSlider" :format-tooltip="formatTooltip" v-model="sliderHeader"></el-slider> </div>
            <div> <i style="cursor:pointer;margin-left:10px" @click="changeSliderBtn(2)" class="el-icon-zoom-in"></i> </div>
        </div>
      </div>
      <div class="header-complete" @click="completeDesign">完成设计</div>
    </div>


    <div class="xp-main">
      <div class="view-content">
        <NoImage @loadingImage='loadingImage' @uploadSuccess='uploadSuccess' v-if="!afterImg"/>
        <!-- <UploadImg v-else :contrast='contrast' @setZoom='setZoom'  :sliderHeader='sliderHeader' ref="handleImg" :afterImg = 'afterImg' :beforeImg = 'beforeImg'/> -->
          <SingleImg  :afterImg='afterImg' v-if="!contrast && afterImg" @setZoom='setZoom' ref="imgContent" :sliderHeader='sliderHeader'/>
          <DoubleImg  :afterImg='afterImg' v-if="contrast && afterImg" :beforeImg='beforeImg' @setZoom='setZoom' ref="doubleContent" :sliderHeader='sliderHeader'/>


      </div>
      <div class="handler-content">
        <HandleParams @uploadSuccess='uploadSuccess' @getImgError='getImgError' ref='setParams'/>
      </div>
    </div>
    <ProgressMain v-if="uploading" :percentage ='percentage'></ProgressMain>
  </div>
</template>

<script>
import UploadImg from './components/uploadImg'
import SingleImg from './components/singleImage'
import DoubleImg from './components/doubleImage'
import ProgressMain from './components/progress'
import NoImage from './components/noImage'
import HandleParams from './components/handleParams'
const BYTES_PER_CHUNK = 1024 * 1024 * 1 / 10; // 每个文件切片大小
import SparkMD5 from "spark-md5";
import { uploadFile, getUploadImage, getUpCode,downLoadFile } from '../../api/axios'
import axios from 'axios'
export default {
  components:{ NoImage, HandleParams, UploadImg, SingleImg, DoubleImg, ProgressMain },
  data() {
    return {
      loadingImg :false,
      contrast: false,
      sliderHeader:50,
      uploadImg:'',
      percentage:0,
      uploading:false,
      index: 1,
      afterImg: '',
      beforeImg: '',
      fileMd5:'',
      url:''
    };
  },
  methods:{
    // 完成设计
    completeDesign(){
      let fileUrl = this.url.split('?')[0]
      let filename = fileUrl;
      let index = filename.lastIndexOf(".");
      let suffix = filename.substr(index+1);
      axios({
          url : `${window.global_url._HOST}/api/Download?filePath=${fileUrl}`,
          responseType:'blob',
          method:'get',
      }).then(res=>{
          if(res.status == 200){
              const aLink = document.createElement("a");
              let blob = new Blob([res.data])
              aLink.href = URL.createObjectURL(blob)
            aLink.setAttribute('download',`定妆照-${new Date().getTime()}.${suffix}`) // 设置下载文件名称
              document.body.appendChild(aLink)
              aLink.click()
              document.body.removeChild(aLink)
          }
      }).catch(err=>{
        console.log(err)
      })
    },
    // 修改拖动条按钮
    changeSliderBtn(v){
      if(!this.afterImg)return
      if(v == 1){
        if(this.sliderHeader == 10)return
        this.sliderHeader -= 2
      }else{
        this.sliderHeader += 2
      }
    },
    getImgError(){
      this.loadingImg = false
      this.index = 1
    },
    uploadSuccess(res){
      this.loadingImg = false
      this.afterImg = ''
      this.beforeImg = ''
      this.url = res.after_url
      this.afterImg = `${this.$api}${res.after_url}`
      this.beforeImg = `${this.$api}${res.before_url}`
      console.log(this.afterImg,'after')
      console.log(this.beforeImg,'beforeimg')
      this.index = 1
    },
    loadingImage(){
      this.loadingImg = true
      this.getImage()
    },
    formatTooltip(val){
      return val * 2
    },
    changeSlider(val){
      if(this.$refs.imgContent){
        this.$refs.imgContent.changeImgSize(val)
      }
      if(this.$refs.doubleContent){
        this.$refs.doubleContent.changeImgSize(val)

      }

      if(this.$refs.handleImg){
        this.$refs.handleImg.changeImg(val * 10 / 2)
      }
    },
    setZoom(zoom){
        this.sliderHeader = zoom * 2 / 10
    },
    changeContrast(val){
      // console.log(this.sliderHeader, 'sliderHeader')
      if(val){
        this.$nextTick(()=>{
          this.$refs.doubleContent.changeImgSize(this.sliderHeader)
        })
      }else{
        this.$nextTick(()=>{
          this.$refs.imgContent.changeImgSize(this.sliderHeader)
        })
      }
    },
    // 更换图片
    changeImage(){
      this.$refs.upload.click()
    },
    async starUpload(){
      let data = new FormData()
      data.append('apikey','70DABA18-3B05-4EB3-B604-04665ABB3FD6')
      let codeResult = await getUpCode(data)
      if(codeResult.traceId){
        this.$notify.error({
          title: `错误,5秒后自动关闭`,
          message: codeResult.detail,
          duration: 5000
        });
        this.loadingImg = false
        return
      }
      this.percentage = 0
      let files = this.$refs.upload.files[0]
      console.log(files,'fielsssss')
      if(!files){
        return
      }
      this.filesSlice(files)
      let file_total = this.paertArr.length
       console.log(file_total,'total')
      // 将进度条分成 total 分
      let singleProgress = Math.ceil(100 / file_total)
      console.log(singleProgress,'singleprogress')
      await this.doIncrementalTest(this.$refs.upload.files[0])
      this.index = 1
      this.Upload(this.paertArr, this.index , files.size , file_total, files.name, singleProgress)
    },
    async Upload(arr, index, size , total, name, singleProgress){
      this.uploading = true
      let formdata = new FormData()
      formdata.append('apikey', '70DABA18-3B05-4EB3-B604-04665ABB3FD6')
      formdata.append('file_size', size)
      formdata.append('file_md5',this.fileMd5)
      formdata.append('file_total', total)
      formdata.append('file_name', name)
      formdata.append('file_index', index)
      formdata.append('file_data',arr[index - 1])
      await uploadFile(formdata).then(res=>{
        if(res.traceId){
          this.$notify.error({
                title: `错误,5秒后自动关闭`,
                message: res.detail,
                duration: 5000
          });
          this.loadingImg = false
          this.uploading = false
          return
        }
        if(res.status == 1){
          this.percentage += singleProgress
          if(this.percentage>=100){
            this.percentage = 99
          }
          this.Upload(arr, index+1, size, total, name, singleProgress)
        }else{
          this.percentage = 100
          this.loadingImg = true
          this.uploading = false
          this.getImage()
        }
      })
    },
    async getImage(){
      this.$refs.setParams.changeSlider()
    },
    doIncrementalTest(input) {
      var _this = this;
      var running = false; //running用于判断是否正在计算md5
      //这里假设直接将文件选择框的dom引用传入
      if (running) {
        return;
      }
      //这里需要用到File的slice( )方法，以下是兼容写法
      var blobSlice =
          File.prototype.slice ||
          File.prototype.mozSlice ||
          File.prototype.webkitSlice,
        file = input,
        chunkSize =104857.6, // 以每片1MB大小来逐次读取
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5()
        return new Promise((resolve, reject) => {
            let fileReader = new FileReader();
              fileReader.onload = function(e) {
              spark.appendBinary(e.target.result); // append array buffer
              currentChunk += 1;
              if (currentChunk < chunks) {
                loadNext();
              } else {
                running = false;
                let str = spark.end();
                _this.fileMd5 = str;//赋值md5
                resolve(str)
                return spark.end(); // 完成计算，返回结果
              }
            };
            fileReader.onerror = function() {
              running = false;
              console.log("something went wrong");
            };
            function loadNext() {
              var start = currentChunk * chunkSize,
                end = start + chunkSize >= file.size ? file.size : start + chunkSize;
              fileReader.readAsBinaryString(blobSlice.call(file, start, end));
            }
            running = true;
            loadNext();
        })
    //   console.log("spark============", spark);
    //   console.log("*************", spark.end());
    },

    filesSlice(files) {
      let start = 0;
      let end;
      let partNumber = 0;
      let part = "";
      let paertArr = [];
      let slices = Math.ceil(files.size / BYTES_PER_CHUNK);
      while (start < files.size) {
        end = start + BYTES_PER_CHUNK;
        if (end > files.size) {
          end = files.size;
        }
        var chunk = files.slice(start, end); //切割文件
        paertArr.push(chunk);
        start = end;
        partNumber++;
      }
      this.paertArr = paertArr;
    }
  }
};
</script>

<style lang='scss' scoped>
.xp-main{
  display: flex;
  background-color: #ebebef;
  .view-content{
    width: 80%;
    height: calc(100vh - 60px);
    background-color: #ebebef;
    padding: 10px;
  }

  .handler-content{
    width: 19%;
    height: calc(100vh - 60px);
    background-color: #ebebef;
    padding: 10px;
  }

}
.cover-image {
  font-size: 14px;
}
.hc-header {
  background-color: #ffe329;
  height: 40px;
  padding: 0 20px;
  line-height: 40px;
  display: flex;
  justify-content: space-between;
  .header-left {
    display: flex;
    align-items: center;
    justify-content: center;
    .header-item {
      margin-right: 30px;
    }
    .header-slider{
        width: 300px;
        display: flex;
        justify-content: space-around;
    }
  }
  .header-complete{
    cursor: pointer;
  }
}
</style>